/*
 * InvertedIndex.cc
 *
 *  Created on: Mar 8, 2013
 *      Author: neo
 */

#include <cassert>
#include <cstdlib>

#include "../report-model/AbstractBugReport.h"
#include "../report-model/Term.h"
#include "InvertedIndex.h"
#include "Postings.h"

InvertedIndex::InvertedIndex(int max_term_id)
    : m_index(static_cast<size_t>(max_term_id + 1),
        static_cast<Postings*>(NULL)) {
}

InvertedIndex::~InvertedIndex() {
  for (vector<Postings*>::iterator iter = this->m_index.begin(), end =
      this->m_index.end(); iter != end; ++iter) {
    Postings* postings = *iter;
    if (postings)
      delete postings;
    *iter = NULL;
  }
}

Postings* InvertedIndex::get_postings(const Term& term) {
  const int id = term.get_tid();
  Postings* postings = this->m_index[id];
  if (!postings) {
    postings = new Postings(id);
    this->m_index[id] = postings;
  }
  assert(postings->get_term_id() == id);
  return postings;
}

void InvertedIndex::get_reports(const vector<Term>& terms,
    vector<AbstractBugReport*>& candidate_collector) {
  assert(candidate_collector.empty());

  for (vector<Term>::const_iterator iter = terms.begin(), end = terms.end();
      iter != end; ++iter) {
    const Term& term = *iter;
    const Postings& postings = *this->get_postings(term);

    const vector<TermInReport>& reports = postings.get_terms();
    for (vector<TermInReport>::const_iterator riter = reports.begin(), rend =
        reports.end(); riter != rend; ++riter) {
      const TermInReport& report = *riter;
    }
  }
}

void InvertedIndex::add_report(const vector<Term>& terms,
    AbstractBugReport& bug_report) {
  for (vector<Term>::const_iterator iter = terms.begin(), end = terms.end();
      iter != end; ++iter) {
    const Term& term = *iter;
    Postings* postings = this->get_postings(term);
    postings->add_report(term, bug_report);
  }
}

